import { ChangeEvent, useState, useCallback, useEffect, useRef } from 'react'
import useBoardStore from '@/store/board'
import { useTranslation } from 'react-i18next'
import { ActionMode } from '@/constants'
import { paintBoard } from '@/core/paintBoard'
import { isMobile as isMobileFn } from '@/utils'
import UndoIcon from '@/components/icons/boardOperation/undo.svg?react'
import RedoIcon from '@/components/icons/boardOperation/redo.svg?react'
import SaveIcon from '@/components/icons/boardOperation/save.svg?react'
import Select from '@/components/icons/select.svg?react'
import CleanIcon from '@/components/icons/boardOperation/clean.svg?react'
import UploadIcon from '@/components/icons/boardOperation/upload.svg?react'
import CopyIcon from '@/components/icons/boardOperation/copy.svg?react'
import TextIcon from '@/components/icons/boardOperation/text.svg?react'
import DeleteIcon from '@/components/icons/boardOperation/delete.svg?react'
import FileListIcon from '@/components/icons/boardOperation/fileList.svg?react'
import FullscreenIcon from '@/components/icons/boardOperation/fullscreen.svg?react'
import FullscreenExitIcon from '@/components/icons/boardOperation/fullscreen-exit.svg?react'
import CloseIcon from '@/components/icons/close.svg?react'
import MenuIcon from '@/components/icons/menu.svg?react'
import FileList from './fileList'
import DownloadImage from './downloadImage'
import UploadImage from './uploadImage'
import { ImageElement } from '@/core/element/image'
import AddFileIcon from '@/components/icons/fileList/addFile.svg?react'
import RemoveFileIcon from '@/components/icons/fileList/removeFile.svg?react'
import ExportFileIcon from '@/components/icons/fileList/exportFile.svg?react'
import ImportFileIcon from '@/components/icons/fileList/importFile.svg?react'
import useFileStore from '@/store/files'
import { set } from 'lodash'
import { Tooltip } from 'antd'

const isMobile = isMobileFn()

const BoardOperation = () => {
  const {
    files,
    currentId,
    updateCurrentFile,
    updateTitle,
    addFile,
    saveJSON,
    uploadFile
  } = useFileStore()

  const { t } = useTranslation()
  const { mode } = useBoardStore()
  const [showFile, updateShowFile] = useState(false) // show file list draw
  const [showOperation, setShowOperation] = useState(true) // mobile: show all operation
  const [isFullscreen, setIsFullscreen] = useState(false)

  const [downloadImageURL, setDownloadImageURL] = useState('')
  const [showDownloadModal, setShowDownloadModal] = useState(false)

  const [uploadImageURL, setUploadImageURL] = useState('')
  const [showUploadModal, setShowUploadModal] = useState(false)

  // toggle fullscreen mode
  const toggleFullscreen = useCallback(async () => {
    try {
      if (!document.fullscreenElement) {
        await document.documentElement.requestFullscreen()
      } else {
        await document.exitFullscreen()
      }
    } catch (err) {
      console.error('fullscreen error:', err)
    }
  }, [])

  /**
   * listen fullscreen event
   * 1. browser behavior
   * 2. toggleFullscreen trigger
   */
  useEffect(() => {
    const handleFullscreenChange = () => {
      setIsFullscreen(!!document.fullscreenElement)
    }

    document.addEventListener('fullscreenchange', handleFullscreenChange)
    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange)
    }
  }, [])
  useEffect(() => {
    console.log('mode change:', mode)
    // if (isMobile) {
    //   if ([ActionMode.DRAW, ActionMode.ERASE].includes(mode)) {
    //     setShowOperation(false)
    //   } else {
    //     setShowOperation(true)
    //   }
    // }
    switch (mode) {
      case ActionMode.DRAW:
        setToolType('draw')
        istoolType.current = 'draw'
        break
      case ActionMode.ERASE:
        setToolType('eraser')
        istoolType.current = 'eraser'

        break
      case ActionMode.SELECT:
        setToolType('updateModeSelect')
        istoolType.current = 'updateModeSelect'
        break
      case ActionMode.Board:
        setToolType('')
        break
      default:
        setShowOperation(true)
        break
    }
  }, [mode])
  // const toolType = useRef('');
  const [toolType, setToolType] = useState('')
  useEffect(() => {
    window.addEventListener('keydown', handleKeyDown);
    mousemoveEvent();
  }, []); // 空依赖数组意味着这个effect只在组件挂载时运行
  const mousemoveEvent = () => {
    const canvas = paintBoard.canvas
    if (!canvas) {
      return
    }
    canvas?.on('mouse:move', (e) => {
      if (istoolType.current == 'text') {
        canvas.defaultCursor = 'text'
      } else if (istoolType.current == 'draw') {
        canvas.defaultCursor = 'crosshair'

      } else {
        canvas.defaultCursor = 'default'
      }
    })
  }
  const handleKeyDown = (event: any) => {
    console.log('Global key pressed:', event.key);
    // 在这里添加你的逻辑
    event.preventDefault()
    switch (event.key) {
      case 'Delete':
        toolClick('deleteObject')
        break;
      case 'z':
        if (event.ctrlKey || event.metaKey) {
          toolClick('undo')
        }
        break;
      case 'y':
        if (event.ctrlKey || event.metaKey) {
          toolClick('redo')
        }
        break;
      case 'd':
        if (event.ctrlKey || event.metaKey) {
          toolClick('draw')
        }
        break;
      case 'i':
        if (event.ctrlKey || event.metaKey) {
          toolClick('text')
        }
        break;
      case 'c':
        if (event.ctrlKey || event.metaKey) {
          toolClick('clean')
        }
        break;
      case 'v':
        if (event.ctrlKey || event.metaKey) {

          toolClick('copyObject')
        }
        break;
      case 'e':
        if (event.ctrlKey || event.metaKey) {
          toolClick('eraser')
        }
        break;
      case 'a':
        if (event.ctrlKey || event.metaKey) {
          toolClick('updateModeSelect')
        }
        break;
    };
  }
  const istoolType = useRef('');
  const toolClick = (type: string) => {
    setToolType(type)
    istoolType.current = type
    if (type === 'undo') {
      undo()
    } else if (type === 'redo') {
      redo()
    } else if (type === 'copyObject') {
      copyObject()
    } else if (type === 'deleteObject') {
      deleteObject()
    } else if (type === 'text') {
      inputText()
    } else if (type === 'image') {
    } else if (type === 'saveImage') {
      saveImage()
    } else if (type === 'updateModeSelect') {
      updateMode(ActionMode.SELECT)
    } else if (type === 'clean') {
      // show clean modal
      const cleanModal = document.getElementById('clean-modal') as HTMLInputElement
      if (cleanModal) {
        cleanModal.checked = true
      }
    } else if (type === 'fileList') {
      updateShowFile(!showFile)
    } else if (type === 'addFile') {
      addFile()
    } else if (type === 'exportFile') {
      saveJSON()
    } else if (type === 'importFile') {
      const importFile = document.getElementById('import-file') as HTMLInputElement
      if (importFile) {
        importFile.value = ''
        importFile.click()
      }
    } else if (type === 'removeFile') {
      const removeFileModal = document.getElementById('remove-file-modal') as HTMLInputElement
      if (removeFileModal) {
        removeFileModal.checked = true
      }
    } else if (type === 'fullscreen') {
      toggleFullscreen()
    } else if (type === 'draw') {
      updateMode(ActionMode.DRAW)
    } else if (type === 'eraser') {
      updateMode(ActionMode.ERASE)
    }

  }
  // copy activity object
  const copyObject = () => {
    paintBoard.copyObject()
  }

  // delete activity object
  const deleteObject = () => {
    paintBoard.deleteObject()
  }

  // click undo
  const undo = () => {
    paintBoard.history?.undo()
  }

  // click redo
  const redo = () => {
    paintBoard.history?.redo()
  }

  // load IText object
  const inputText = () => {
    const canvas = paintBoard.canvas
    canvas?.on('mouse:down', (e) => {
      if (istoolType.current == 'text') {
        toolClick('updateModeSelect')
        if (e?.absolutePointer) {
          const { x, y } = e.absolutePointer
          paintBoard.textElement?.loadText(x, y)
        }
      }
    })
  }

  // upload image file
  const uploadImage = (e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) {
      return
    }

    const reader = new FileReader()
    reader.onload = (fEvent) => {
      const data = fEvent.target?.result
      if (data) {
        if (data && typeof data === 'string') {
          console.log('upload image:', data)
          // setUploadImageURL(data)
          // setShowUploadModal(true)
          uploadImages(data)
        }
      }
      e.target.value = ''
    }
    reader.readAsDataURL(file)
  }
  const uploadImages = (url: any) => {
    const image = new ImageElement()
    image.addImage(url)
  }
  // save as image
  const saveImage = () => {
    if (paintBoard.canvas) {
      const url = paintBoard.canvas.toDataURL()
      setDownloadImageURL(url)
      setShowDownloadModal(true)
    }
  }
  const { updateMode } = useBoardStore()
  return (
    <>
      <div className='tool-btn-box fixed top-10 left-2/4 -translate-x-2/4 flex items-center'>
        <div
          onClick={() => toolClick('undo')}
          className={`tool-item min-xs:tooltip cursor-pointer ${istoolType.current === 'undo' ? 'tool-item-on' : ''}`}
          data-tip={t('operate.undo')}
        >
          <i className='Ticonfont Ticon-Edit_shangyibu_back_linear'></i>
          <span className='keydown'>z</span>
        </div>
        <div
          onClick={() => toolClick('redo')}
          className={`tool-item min-xs:tooltip cursor-pointer ${istoolType.current === 'redo' ? 'tool-item-on' : ''}`}
          data-tip={t('operate.redo')}
        >
          <i className='Ticonfont Ticon-Edit_xiayibu_next_linear'></i>
          <span className='keydown'>y</span>
        </div>
        <div
          onClick={() => toolClick('draw')}
          className={`tool-item min-xs:tooltip cursor-pointer ${istoolType.current === 'draw' ? 'tool-item-on' : ''}`}
          data-tip={'绘制'}
        >
          <i className='Ticonfont Ticon-huizhi'></i>
          <span className='keydown'>d</span>
        </div>
        <div
          onClick={() => toolClick('copyObject')}
          className={`tool-item min-xs:tooltip cursor-pointer ${istoolType.current === 'copyObject' ? 'tool-item-on' : ''}`}
          data-tip={t('operate.copy')}
        >
          <i className='Ticonfont Ticon-fuzhi'></i>
          <span className='keydown'>v</span>
        </div>
        <div
          onClick={() => toolClick('text')}
          className={`tool-item min-xs:tooltip cursor-pointer ${istoolType.current === 'text' ? 'tool-item-on' : ''}`}
          data-tip={t('operate.text')}
        >
          <i className='Ticonfont Ticon-wenzi'></i>
          <span className='keydown'>i</span>
        </div>
        <div
          onClick={() => toolClick('image')}
          className={`tool-item min-xs:tooltip cursor-pointer ${istoolType.current === 'image' ? 'tool-item-on' : ''}`}
          data-tip={t('operate.image')}
        >
          <label htmlFor="image-upload" className="cursor-pointer">
            <i className='Ticonfont Ticon-tupianshangchuan'></i>
          </label>
          <input
            type="file"
            id="image-upload"
            accept=".jpeg, .jpg, .png"
            className="hidden"
            onChange={uploadImage}
          />
        </div>
        <div
          onClick={() => toolClick('clean')}
          className={`tool-item min-xs:tooltip cursor-pointer ${istoolType.current === 'clean' ? 'tool-item-on' : ''}`}
          data-tip={t('operate.clean')}
        >
          <i className='Ticonfont Ticon-qingkong'></i>
          <span className='keydown' >c</span>
        </div>
        <div
          onClick={() => toolClick('updateModeSelect')}
          className={`tool-item min-xs:tooltip cursor-pointer ${istoolType.current === 'updateModeSelect' ? 'tool-item-on' : ''}`}
          data-tip={'选择'}
        >
          <i className='Ticonfont Ticon-xuanze'></i>
          <span className='keydown'>A</span>
        </div>
        <div
          onClick={() => toolClick('deleteObject')}
          className={`tool-item min-xs:tooltip cursor-pointer ${istoolType.current === 'deleteObject' ? 'tool-item-on' : ''}`}
          data-tip={t('operate.delete')}
        >
          <i className='Ticonfont Ticon-shanchu'></i>
          <span className='keydown'>del</span>
        </div>
        <div
          onClick={() => toolClick('eraser')}
          className={`tool-item min-xs:tooltip cursor-pointer ${istoolType.current === 'eraser' ? 'tool-item-on' : ''}`}
          data-tip={'橡皮擦'}
        >
          <i className='Ticonfont Ticon-rubber-full'></i>
          <span className='keydown'>e</span>
        </div>
            <Tooltip placement="topRight" title={'ctrl+控制键实现快捷切换'}>
          <i className='Ticonfont Ticon-bangzhu'></i>
        </Tooltip>
      </div >
    
      {showFile && <FileList updateShow={updateShowFile} />
      }
      {
        showDownloadModal && downloadImageURL && (
          <DownloadImage
            url={downloadImageURL}
            showModal={showDownloadModal}
            setShowModal={setShowDownloadModal}
          />
        )
      }
      <UploadImage
        url={uploadImageURL}
        showModal={showUploadModal}
        setShowModal={setShowUploadModal}
      />
    </>
  )
}

export default BoardOperation
